//导入db模块
const db = require('../common/db/index')
//导入加密模块
const aes = require('../common/aes/index')

//定义用户类
class User {
  //注册
  register(user_name, user_email, user_phone, user_password) {
    return new Promise((resolve, reject) => {
      // 执行查询用户sql语句
      //  db.query(`select 字段  from  数据表   where 字段=值`)
      db.query(`select user_phone from user where user_phone='${user_phone}'`)
        .then(
          rows => {
            if (rows.length == 0) {
              // 未注册
              // 对密码进行加密
              let pwd = aes.aesEncrypt(user_password)
              // 记录用户注册的时间
              let date = new Date()
              let time = date.getTime()//时间戳（以后可以根据时间戳获取年月日时分秒）
              let num = Math.floor(Math.random() * 5 + 1)
              let imgUrl = `/static/images/${num}.jpg`
              // 执行插入数据的sql语句
              db.query(`insert into user(user_name,user_email,user_phone,user_password,createAt,imgUrl) values('${user_name}','${user_email}','${user_phone}','${pwd}','${time}','${imgUrl}')`)
                .then(
                  content => {
                    resolve({
                      code: 200,
                      msg: "恭喜您，注册账号成功",
                      status: content.changedRows == 0 ? '正常' : '异常'
                    })
                  },
                  err => {
                    reject({
                      code: -1,
                      msg: "注册失败",
                      err
                    })
                  }
                )

            }
            else {
              // 已注册
              resolve({
                code: 1,
                msg: `该账号已存在,${account}`
              })
            }
          },
          err => {
            //  出现异常
            reject({
              code: 500,
              msg: "后台出现异常",
              err
            })
          }
        )
    })
  }
  //登录
  login(user_phone, user_password) {
    return new Promise((resolve, reject) => {
      // 使用参数化查询，以防止 SQL 注入
      db.query(`SELECT user_phone, user_password, id, user_name FROM user WHERE user_phone = ${user_phone}`)
        .then(rows => {
          if (rows.length === 0) {
            resolve({
              code: 404,
              msg: `该账号不存在，${user_phone}`
            });
          } else {
            // 解构赋值
            let [user] = rows;

            if (user.user_password) {
              // 解密密码并验证
              let isLogin = aes.aesDecrypt(user_password, user.user_password);
              if (isLogin) {
                // 登录成功
                resolve({
                  code: 200,
                  msg: `${user_phone}, 登录成功`,
                  id: user.id,
                  nickName: user.user_name // 使用用户名称字段
                });
              } else {
                // 密码错误
                resolve({
                  code: -1,
                  msg: `账号或密码错误`
                });
              }
            }
          }
        })
        .catch(err => {
          reject({
            code: 500,
            msg: "后台发生错误",
            err
          });
        });
    });
  }
  //修改密码
  pwd(user_email, user_password) {
    return new Promise((resolve, reject) => {
      db.query(`select user_email from user where user_email='${user_email}'`)
        .then(
          rows => {
            if (rows.length == 0) {
              // 不存在
              resolve({
                code: -1,
                msg: "该账号不存在"
              })
            }
            else {
              // 存在
              // 对密码进行加密
              let pwd = aes.aesEncrypt(user_password)
              db.query(`update user set user_password= '${pwd}' where user_email= '${user_email}'`)
                .then(
                  content => {
                    resolve({
                      code: 200,
                      msg: `设置用户密码成功`,
                      status: content.fieldCount === 0 ? '正常' : '异常'
                    })
                  },
                  error => {
                    reject({
                      code: -1,
                      msg: "服务端发生错误",
                      error
                    })
                  }
                )
            }
          },
          err => {
            reject({
              code: -1,
              msg: "服务端发生错误",
              err
            })
          }
        )
    })
  }
  // 获取用户详情信息
  info(id) {
    return new Promise((resolve, reject) => {
      db.query(`select * from user where id='${id}'`)
        .then(
          rows => {
            if (rows.length == 0) {
              resolve({
                code: -1,
                msg: "该账号不存在"
              })
            }
            else {
              resolve({
                code: 200,
                result: [...rows]
              })
            }
          },
          err => {
            reject({
              code: -1,
              msg: "服务端发生错误",
              err
            })
          }
        )
    })
  }
  // 编写用户信息
  edit(id,user_name,user_email,user_phone,user_sex) {
    return new Promise((resolve, reject) => {
      db.query(`select user_email from user where id='${id}'`)
        .then(
          rows => {
            if (rows.length == 0) {
              // 不存在
              resolve({
                code: -1,
                msg: "该账号不存在"
              })
            }
            else {
              // 存在
              db.query(`update user set user_name= '${user_name}',user_email= '${user_email}',user_phone= '${user_phone}' ,user_sex= '${user_sex}' where id= '${id}'`)
                .then(
                  content => {
                    resolve({
                      code: 200,
                      msg: `设置用户信息成功`,
                      status: content.fieldCount === 0 ? '正常' : '异常'
                    })
                  },
                  error => {
                    reject({
                      code: -1,
                      msg: "服务端发生错误",
                      error
                    })
                  }
                )
            }
          },
          err => {
            reject({
              code: -1,
              msg: "服务端发生错误",
              err
            })
          }
        )
    })
  }
  //添加记账信息
  
}

//把这个类挂在模块系统上
module.exports = User